package com.weimei.conversionTreasure.viewModel;

import android.app.Activity;
import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.databinding.ObservableList;

import com.chad.library.BR;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieEntry;
import com.lxj.xpopup.XPopup;
import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.http.entity.MonthBean;
import com.weimei.conversionTreasure.http.entity.YearBean;
import com.weimei.conversionTreasure.utils.ChartUtils;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.weight.BottomTimePop;
import com.weimei.conversionTreasure.weight.BottomWheelPop;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class TotalVM extends TitleVM{
    public TotalVM(@NonNull Application application, BaseModel model) {
        super(application, model);
        titleVM.setTitleText("统计详情");
        if (type.get().equals("0")){
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            time.set(year+"-"+month);
        }else {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            time.set(year+"");
        }
    }

    PieChart pieChart;
    public void setPieView(PieChart totalPie) {
        this.pieChart = totalPie;

    }

    ArrayList<PieEntry> pieMList = new ArrayList<>();
    ArrayList<PieEntry> pieYList = new ArrayList<>();


    public ObservableField<String> type = new ObservableField<>("0");

    public ObservableField<String> time = new ObservableField<>("0");
    public ObservableField<String> types = new ObservableField<>("支出");
    public ObservableField<String> monthOrderBy = new ObservableField<>("");

    public ObservableField<String> sumZc = new ObservableField<>("");
    public ObservableField<String> zTxt = new ObservableField<>("总支出:");

    public ObservableInt yrecy = new ObservableInt(View.GONE);
    public ObservableInt mrecy = new ObservableInt(View.VISIBLE);


    Activity mActivity;
    @Override
    public void setActivity(Activity activity) {
        super.setActivity(activity);
        this.mActivity = activity;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (type.get().equals("0")){
            mrecy.set(View.VISIBLE);
            yrecy.set(View.GONE);
            getMonthData();
        }else {
            mrecy.set(View.GONE);
            yrecy.set(View.VISIBLE);
            getYearData();
        }
    }

    public BindingCommand typePick=  new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            List<String> list = new ArrayList<>();
            list.add("支出");
            list.add("收益");
            new XPopup.Builder(mActivity)
                    .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                    .enableDrag(true)
                    .asCustom(new BottomWheelPop(mActivity,list, s1 -> {
                        types.set(s1);
                        zTxt.set("总"+s1+":");
                        onResume();
                    }))
                    .show();
        }
    });

    public BindingCommand leftClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (type.get().equals("0")){
                int curDate;
                if (time.get().length() == 6){
                     curDate = Integer.parseInt(time.get().substring(5,6));
                }else {
                     curDate = Integer.parseInt(time.get().substring(5,7));
                }
                int js = curDate -1;
                if (js > 0){
                    time.set(time.get().substring(0,4)+"-"+js+"");
                }

            }else {
                int curDate = Integer.parseInt(time.get());
                time.set(curDate -1+"");

            }
            onResume();

        }
    });

    public BindingCommand rightClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (type.get().equals("0")){
                int curDate;
                if (time.get().length() == 6){
                    curDate = Integer.parseInt(time.get().substring(5,6));
                }else {
                    curDate = Integer.parseInt(time.get().substring(5,7));
                }
                int js = curDate+1;
                if (js <= 12){
                    time.set(time.get().substring(0,4)+"-"+js+"");
                }

            }else {
                int curDate = Integer.parseInt(time.get());
                time.set(curDate +1+"");

            }
            onResume();
        }
    });


    public BindingCommand timePick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (type.get().equals("0")){
                pickYM();
            }else {
                pickY();
            }
        }
    });

    private void pickY() {
        new XPopup.Builder(mActivity)
                .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                .enableDrag(true)
                .asCustom(new BottomTimePop(mActivity, s1 -> {
                    time.set(s1);
                    onResume();
                },false,false))
                .show();
    }

    private void pickYM() {
        new XPopup.Builder(mActivity)
                .moveUpToKeyboard(false)//如果不加这个，评论弹窗会移动到软键盘上面
                .enableDrag(true)
                .asCustom(new BottomTimePop(mActivity, s1 -> {
                    time.set(s1);
                    onResume();
                },true,false))
                .show();
    }


    public ObservableList<TotalYItemVM> observableListY = new ObservableArrayList<>();
    public ItemBinding<TotalYItemVM> itemBindingY = ItemBinding.of(BR.viewModel,R.layout.item_total_y);

    private void getYearData() {
        observableListY.clear();
        pieYList.clear();
        Map<String,String> map = new HashMap<>();
         map.put("user_id", UserUtils.getUserAccount());
        map.put("YearValue", time.get());
        map.put("types", types.get());

        model.year_chart(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<YearBean>() {
                    @Override
                    public void onNext(YearBean bean) {
                        if (bean.issucc){
                            sumZc.set(bean.getData().getSumAmount()+"");
                            if (bean.getData().getMlist().size() > 0){
                                for (YearBean.DataDTO.MlistDTO data: bean.getData().getMlist() ) {
                                    TotalYItemVM itemVM = new TotalYItemVM(TotalVM.this,data);
                                    itemVM.setTime(types.get());
                                    observableListY.add(itemVM);

                                    PieEntry pieEntry = new PieEntry(
                                            Float.parseFloat(data.getRatio().replace("%","")),
                                            data.getMonth() + "-" + data.getRatio());
                                    pieYList.add(pieEntry);

                                }

                            }
                            ChartUtils.setPieData(pieChart, "type", "num", pieYList);

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public ObservableList<TotalMItemVM> observableListM = new ObservableArrayList<>();
    public ItemBinding<TotalMItemVM> itemBindingM = ItemBinding.of(BR.viewModel,R.layout.item_total_m);

    public void getMonthData(){
        observableListM.clear();
        pieMList.clear();
        Map<String,String> map = new HashMap<>();
         map.put("user_id", UserUtils.getUserAccount());
        map.put("date", time.get());
        map.put("types", types.get());

        model.monthly_stat(map)
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .doOnSubscribe(this)
                .doOnSubscribe(disposable -> {})
                .subscribe(new DisposableObserver<MonthBean>() {
                    @Override
                    public void onNext(MonthBean bean) {
                        if (bean.issucc){
                            sumZc.set(bean.getData().getPriceSum()+"");
                            if (bean.getData().getClist().size() > 0){
                                for (MonthBean.DataDTO.ClistDTO data: bean.getData().getClist()) {
                                    TotalMItemVM itemVM = new TotalMItemVM(TotalVM.this,data);
                                    itemVM.setTime(types.get(),time.get());
                                    observableListM.add(itemVM);

                                    PieEntry pieEntry = new PieEntry(
                                            Float.parseFloat(data.getRatio().replace("%","")),
                                            data.getClassName() + "-" + data.getRatio());
                                    pieMList.add(pieEntry);

                                }

                            }
                            ChartUtils.setPieData(pieChart, "type", "num", pieMList);

                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
